import 'dart:async';

import 'package:flutter/material.dart';

class BlocDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return CounterProvider(
      widget: Scaffold(
        appBar: AppBar(
          title: Text('Bloc Demo'),
          elevation: 0.0,
        ),
        floatingActionButton: CounterFloatingActionButton(),
        body: BlocDemoHome(),
      ),
      counterBloc: CounterBloc(),
    );
  }
}

class CounterFloatingActionButton extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    CounterBloc counterBloc = CounterProvider.of(context).counterBloc;
    return FloatingActionButton(
      child: Icon(Icons.add),
      onPressed: () {
        counterBloc.count.add(1);
      },
    );
  }
}

class BlocDemoHome extends StatelessWidget {


  @override
  Widget build(BuildContext context) {
    CounterBloc counterBloc = CounterProvider.of(context).counterBloc;

    return Center(
        child: StreamBuilder(
      initialData: 0,
      stream: counterBloc.stream,
      builder: (context, snapshot) {
        return ActionChip(
          label: Text('${snapshot.data}'),
          onPressed: () {
//          counterBloc.log();
            counterBloc.count.add(1);
          },
        );
      },
    ));
  }
}

class CounterBloc {
  int _count = 0;
  final counterController = StreamController<int>();
  final actionController = StreamController<int>();


  Stream<int> get stream => actionController.stream;

  StreamSink<int> get count =>
      counterController.sink; //get 方法 从counterController 中获取sink

  CounterBloc() {
    counterController.stream.listen(onData);
  }

  void onData(int data) {
//    print('$data');
    _count = _count + data;
    actionController.add(_count);
  }

  void log() {
    print('blog');
  }

  void dispose() {
    counterController.close();
    actionController.close();
  }
}

class CounterProvider extends InheritedWidget {
  final Widget widget;
  final CounterBloc counterBloc;

  CounterProvider({this.widget, this.counterBloc}) : super(child: widget);

  static CounterProvider of(BuildContext context) =>
      context.inheritFromWidgetOfExactType(CounterProvider);

  @override
  bool updateShouldNotify(InheritedWidget oldWidget) {
    return true;
  }
}
